<template>
    <div class="layout-padding">
        <div class="layout-padding-auto layout-padding-view">
            <!--  标题行    -->
            <el-row :gutter="20" style="margin: 0px -10px 20px 5px;">
                <el-col :span="20"><h1 class="my-heading">上传资料</h1></el-col>
                <el-col :span="1.5"><el-button @click="uploadSysFileSubmit">保存</el-button></el-col>
                <el-col :span="1.5"><el-button @click="goBack">返回</el-button></el-col>
            </el-row>
            <!--    条件行   -->
            <el-row v-show="showSearch">
                <el-form :model="queryForm" :rules="queryFormRules" ref="queryRef" :inline="true" @keyup.enter="getDataList">
                    <el-row>
                        <el-text  style="color: red">(如需新增专业信息,请先新增专业信息内容)</el-text>
                    </el-row>
                    <el-button  type="primary" size="small"  :visible.sync="centerDialogVisible"
                                @click="centerDialogVisible=true" style="margin-top: -15px"
                                :disabled="isDisabled">新增专业信息</el-button>
                    <el-form-item label="参与组织" prop="studyGroupId" style="width: 420px">
                        <el-cascader v-model="queryForm.studyGroupId" ref="cascaderAddr"  :options="options1"  filterable clearable style="width: 420px" @visible-change="handleVisibleChange"
                                placeholder="请选择标签" @change="handleCascaderChange" :props="{ value: 'id', label: 'name', children: 'children',checkStrictly: true }">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="参与岗位" prop="studyPosts" style="width: 320px">
                        <el-select  @change="getItem1" v-model="queryForm.studyPosts" filterable clearable multiple collapse-tags collapse-tags-tooltip  placeholder="请选择" style="width: 240px">
                            <el-option v-for="item in postList" :key="item.postsString" :label="item.postName" :value="item.postName"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="专业名称" prop="majorNameIds" style="width: 320px">
                        <el-select @change="getItem3" v-model="queryForm.majorNameIds" filterable clearable multiple collapse-tags collapse-tags-tooltip  placeholder="请选择" style="width: 240px">
                            <el-option v-for="item in options2"  :key="item.zymcId" :label="item.zymcName" :value="item.zymcId"/>
                        </el-select>
                    </el-form-item>

                    <!--                <el-form-item label="专业等级" prop="dataLevelId" style="margin-left: 15px">-->
                    <!--                    <el-select v-model="state.queryForm.dataLevelId" filterable  style="width: 240px" >-->
                    <!--                        <el-option v-for="item in zydjnamelist"  :key="item.zydjId" :label="item.zydjName" :value="item.zydjId"/>-->
                    <!--                    </el-select>-->
                    <!--                </el-form-item>-->
                    <el-form-item label="关键点" prop="keyPointIds" style="width: 320px">
                        <el-select @change="getItem2" v-model="queryForm.keyPointIds" filterable clearable multiple collapse-tags collapse-tags-tooltip  placeholder="请选择" style="width: 240px">
                            <el-option v-for="item in keypointsListData" :key="item.keyId" :label="item.zymcName+'-'+item.keyPoint" :value="item.keyId"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item style="width: 600px"  v-if="route.query.state=='0'">
                        <!--   上传文件     -->
<!--                        <el-upload ref="upload" class="upload-demo" :file-list="fileList" :class="{hide:fileHide}"  style="width: 600px"-->
<!--                                   :on-change="handleChange" :on-remove="fileRemove" action="#" :auto-upload="false">-->
<!--                            <el-button size="small" type="primary">点击上传</el-button>-->
<!--                        <el-text style="margin-left: 30px;color: #7B7B7B;font-size: 12px"> 上传的资料可以是视频、音频、图片、文档（word、excel、ppt、pdf、txt）.</el-text>-->
<!--                        </el-upload>-->
                        <el-upload :file-list="fileList" class="upload-demo"  :action="officeUrl + '/uploadFile'"   multiple :on-success="getFile" style="width: 600px">
                            <el-button type="primary" style="margin-top: 10px" :disabled="queryForm.studyGroupId ==undefined ||queryForm.studyPostIds.length ==0 || queryForm.majorNameIds.length ==0 || queryForm.keyPointIds.length ==0">上传</el-button>
                        </el-upload>
                    </el-form-item>
                </el-form>
            </el-row>
            <!--   表格   -->
            <el-table :data="dataList" v-loading="loading" border  :cell-style="tableStyle.cellStyle"
                      @selection-change="selectionChangHandle" @sort-change="sortChangeHandle"   :header-cell-style="rowClass">
                <el-table-column type="selection" width="40" align="center" />
                <el-table-column prop="id" label="#" width="50" />
                <el-table-column prop="fileNameAll" label="上传文件名称"  align="center" show-overflow-tooltip>
<!--                    <template #default="scope" style="text-align: center;">-->
<!--                        <input type="text" v-model="scope.row.fileName" style="width:280px;text-align: right;margin-right: 5px"disabled/>-->
<!--                        <a :href='scope.row.url' target="_blank">预览</a>-->
<!--                    </template>-->
                </el-table-column>
                <el-table-column v-if="route.query.state=='0'"  prop="fileNameView" label="资料名称" align="center"  show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.fileNameView" @blur="updateNotesValue(scope.row)" class="ipt" style="width:100px;text-align: center;" />
                    </template>
                </el-table-column>
                <el-table-column v-else  prop="dataName" label="资料名称" align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.dataName" @blur="updateNotesValue(scope.row)" class="ipt" style="width:100px" />
                    </template>
                </el-table-column>
                <el-table-column  width="100" prop="fileSize" label="文件大小" align="center" show-overflow-tooltip/>
                <el-table-column width="170" prop="minTime" label="最低学习时长(分钟)" align="center"  show-overflow-tooltip>
                    <template #default="scope">
                        <el-input-number v-model="scope.row.minTime" @change="updateNotesValue(scope.row)" :min="1" :max="500"/>
                    </template>
                </el-table-column>
                <el-table-column width="170" prop="timeOut" label="超时提醒时长(分钟)" align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <el-input-number v-model="scope.row.timeOut" @change="updateNotesValue(scope.row)" :min="1" :max="500"/>
                    </template>
                </el-table-column>
                <el-table-column  prop="fileNameView"  label="资料简介(必填)" align="center" show-overflow-tooltip>
                    <template #default="scope">
                        <input type="text" v-model="scope.row.remark"  @blur="updateNotesValue(scope.row)" class="ipt" style="width:100px" />
                    </template>
                </el-table-column>
                <el-table-column width="110" prop="createBy" label="创建人员" align="center" show-overflow-tooltip />
                <el-table-column width="160" prop="createTime" label="创建时间" align="center" show-overflow-tooltip/>
                <el-table-column label="操作" align="center" width="320">
                    <template #default="scope">
                        <el-button type="primary" @click="preview(scope.row)">预览(缓存)
                        </el-button>
                        <el-button type="primary" @click="preview1(scope.row)">编辑/预览
                        </el-button>
                        <el-button icon="edit-pen" text type="primary" v-auth="'train_kszlFile_edit'" @click="formDialogRef.openDialog(queryForm,scope.row)">关联试题</el-button>
                        <el-button icon="delete" v-if="route.query.state!=='1'" text type="primary" v-auth="'train_kszlFile_del'" @click="handleDelete([scope.row.id],scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 创建试题、编辑  -->
        <form-dialog  ref="formDialogRef" @refresh="getDataList(false)" />
        <!-- 新增专业名称、专业等级、关键点  -->
        <el-dialog v-model="centerDialogVisible" title="新增" @close="clean1" width="30%">
            <el-form :model="keypointsform"  :rules="keypointsRules" ref="pointsformlist">
                <el-form-item label="专业名称"   prop="zymcName"  >
                    <el-select @change="getProfessionalGrade" v-model="keypointsform.zymcName" filterable clearable allow-create default-first-option :reserve-keyword="false" style="width: 240px">
                        <el-option v-for="item in options2"  :key="item.zymcId" :label="item.zymcName" :value="item.zymcName"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="专业等级"  prop="zydjName">
                    <el-select @change="getProfessionalGrade1" v-model="keypointsform.zydjName" filterable clearable allow-create default-first-option :reserve-keyword="false" style="width: 240px">
                        <el-option v-for="item in zydjnamelist"  :key="item.zydjId" :label="item.zydjName" :value="item.zydjName"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="关键点"  prop="keyPoint">
                    <el-input v-model="keypointsform.keyPoint" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="备注" :label-width="formLabelWidth" prop="zydjDescription">
                    <el-input v-model="keypointsform.zydjDescription" type="textarea"/>
                </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取消</el-button>
                <el-button type="primary" :visible.sync="centerDialogVisible" @click="onSubmit">提交</el-button>
              </span>
            </template>
        </el-dialog>
        <!-- 题目数量校验  -->
        <el-dialog v-model="centerDialogVisible2"  width="20%">
            <el-text style="color: red;font-weight: bold">{{checkMsg}}资料名称已有重复名称,请改成其他名称后继续保存</el-text>
            <template #footer>
                      <span class="dialog-footer">
                        <el-button type="primary" style="margin-left: -10px;margin-top: -10px" @click="centerDialogVisible2 = false">确认</el-button>
                      </span>
            </template>
        </el-dialog>
        <!-- 文件上传校验  -->
        <el-dialog v-model="centerDialogVisible3"  width="20%">
            <el-text style="color: red;font-weight: bold">文件已有重复名称,上传失败</el-text>
            <template #footer>
                      <span class="dialog-footer">
                        <el-button type="primary" style="margin-left: -10px;margin-top: -10px" @click="submitBtn">确认</el-button>
                      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts" name="systemKszlFile">
    //导入
    import { BasicTableProps, useTable } from "/@/hooks/table";
    import { useMessage, useMessageBox } from "/@/hooks/message";
    import { useDict } from '/@/hooks/dict';
    import { useRouter } from 'vue-router';
    import { Session } from '/@/utils/storage';
    import type { UploadProps, UploadUserFile } from 'element-plus'
    import {ref} from "vue";
    import {useUserInfo} from '/@/stores/userInfo';
    import mittBus from '/@/utils/mitt';
    import {getKeyPointListByZymcIds} from "/@/api/train/ksglExamList";
    import {
        delObjs,
        putObj,
        uploadSysFile,
        uploadSysFileData,
        fileSubmit,
        getAddList,
        saveProfession,
        keypointsList,
        office,
        officeType,
        updateOnlyOffice,
        officeView
    } from "/@/api/train/kszlFile";
    import {deptTree, getEditList, syspost} from "/@/api/train/kszlData";
    import {getLevel, professionalnameList} from "/@/api/train/jnglProfessionLevel";
    import {addobj} from "/@/api/train/jnglKeyPoints";
    import axios from "axios";
    import {checkToken} from "/@/api/login";
    import {ElMessage} from "element-plus";
    // 引入组件
    const FormDialog = defineAsyncComponent(() => import('./form.vue'));
    // 定义查询字典
    const route = useRoute();
    //新增
    const pointsformlist = ref<InstanceType<typeof import('element-plus/es/components/form')>>(null);
    // 定义变量内容
    const formDialogRef = ref()
    // 搜索变量
    const queryRef = ref()
    const currentCell = ref()
    const allUrl = ref()
    const showSearch = ref(true)
    const loading = ref(false)
    // 多选变量
    const selectObjs = ref([]) as any
    const multiple = ref(true)
    //弹框显示
    const dialogVisible = ref(false)
    const centerDialogVisible = ref(false)
    const centerDialogVisible2 = ref(false)
    const centerDialogVisible3 = ref(false)
    const state: BasicTableProps = reactive<BasicTableProps>({
        queryForm: {},
    })
    const studyGroup = ref()
    // 表单元素
    const dom = ref()
    const params = ref()
    const fileData = ref()
    const checkMsg = ref();
    // 校验规则
    const keypointsRules = ref({
        zymcName: [{ required: true, message: '请输入专业名称',trigger: 'change'}],
        zydjName: [{ required: true, message: '请输入专业等级',trigger: 'change'}],
        keyPoint: [{ required: true, message: '请输入关键点',trigger: 'change'}],
    })
    const queryFormRules = ref({
        studyGroupId: [{ required: true, message: '请输入参与组织',trigger: 'change'}],
        studyPosts: [{ required: true, message: '请输入参与岗位',trigger: 'change'}],
        majorNameIds: [{ required: true, message: '请输入专业名称',trigger: 'change'}],
        keyPointIds: [{ required: true, message: '请输入关键点',trigger: 'change'}],
        file:[{ required: true, message: '请上传资料',trigger: 'change'}]
    })
    //新增弹框表单
    const keypointsform = reactive({
        zydjDescription:'',
        zydjId:'',
        zymcId:'',
        zymcName:''
    })
    //  table hook
    const {
        getDataList,
        currentChangeHandle,
        sizeChangeHandle,
        sortChangeHandle,
        downBlobFile,
        tableStyle
    } = useTable(state)
    //返回上一页
    const router = useRouter();
    const goBack = () => {
        router.push('/train/kszlData/index');
    };
    const queryForm =reactive({
        fileIds:[],
        studyPostIds:[],
        majorNameIds:[],
        keyPointIds:[],
    })
    const idsList = reactive([])
    //学习组织数据
    const options1 = ref<any[]>([]);
    //专业名称数据
    const options2 =reactive([])
    const dataList =reactive([{}])
    const falseList =reactive([{}])
    //专业等级
    const zydjnamelist = reactive([])
    const studyGroupNames = ref([])
    const studyGroupIds = ref([])
    //学习岗位
    const postList =reactive([])
    //关键点
    const keypointsListData = reactive([])
    const isDisabled = computed(() => {
        return queryForm.studyGroupId !==undefined ||queryForm.studyPostIds.length !==0 ||
            queryForm.majorNameIds.length !==0 || queryForm.keyPointIds.length !==0
    })
    //部门主键
    const pkDept = ref()
    const officeUrl = ref()
    const random = ref()
    const type = ref()
    const username = ref()
    const officeUrl1 = ref()
    const fileType = ref()
    const number = ref(0)
    const cascaderAddr = ref<InstanceType<typeof import('element-plus/es/components/cascader')>>(null);
    //挂载完毕
    onMounted(()=>{
        // console.log('queryForm',queryForm)
        username.value = useUserInfo().userInfos.user.username
        dataList.length = 0
        queryForm.state =  route.query.state
        office().then((res)=>{
            officeUrl.value = res.data
        })
        officeType().then((res)=>{
            fileType.value =res.data
        })
        officeView().then((res)=>{
            officeUrl1.value = res.data
        })
        if(route.query.state =='1'){
            const id = route.query.id
            const params = `dataFileId=${id}`;
            // console.log('params----',params)
            getEditList(params).then((res)=>{
                Object.assign(dataList, res.data.data)
              // console.log('dataList=======',dataList)
                queryForm.studyGroupIds = dataList[0].studyGroupId.split('/');
                queryForm.studyGroupNames= dataList[0].studyGroup.split('/');
                queryForm.studyGroup= dataList[0].studyGroup
                queryForm.partOrgName= dataList[0].studyGroup//创建试题
                queryForm.partOrgId = dataList[0].studyGroupId//创建试题
                queryForm.studyGroupId = dataList[0].studyGroupId

                queryForm.majorNameIds= dataList[0].majorNameId.split('、');
                queryForm.majorNames= dataList[0].majorName.split('、');

                queryForm.keyPointIds= dataList[0].keyPointId.split('、');
                queryForm.keyPoints= dataList[0].keyPoint.split('、');

                queryForm.studyPosts= dataList[0].studyPost.split('、');
                queryForm.studyPostIds= dataList[0].studyPostId.split('、');

                queryForm.dataLevels =  dataList[0].dataLevel.split('、');
                queryForm.dataLevelIds =  dataList[0].dataLevelId.split('、');
                type.value =  dataList[0].fileName;
                getKeypointsList()
                getPostList()
            });
        }else {
            queryRef.value.resetFields();
        }
        deptTreeList()
        getProfessionalName()
    })
    const  rowClass = ({rowIndex, columnIndex}) => {
        if (rowIndex === 0&&columnIndex===7) {
            return {color:'red',backgroundColor:"#f5f7fa"}
        }else{
            return {color:'black',backgroundColor:"#f5f7fa"}
        }
    }
    const  updateNotesValue = (row:any) =>{
        if(queryForm.state == '0'){
            row.dataName = row.fileNameView
        }
        putObj(row)
    }
    //预览同步
    const preview = (row:any) => {
        // let baseURL = import.meta.env.VITE_API_URL;
        // window.open(baseURL+ row.fileAddress)
        let originalUrl = `${officeUrl.value}/downloadFilec?id=${row.onlyOfficeId}`;
        let previewUrl  = originalUrl +  `&fullfilename=${row.id}${row.fileName}`
        // console.log('previewUrl',previewUrl)
        //转换为 Base64 编码
        let base64EncodedUrl = btoa(previewUrl);
        //使用 encodeURIComponent 编码
        let encodedUrl = encodeURIComponent(base64EncodedUrl);
        allUrl.value = officeUrl1.value + encodedUrl
        window.open(allUrl.value);
    }
    //预览快速
    const preview0 = (row:any) => {
        const url = `${officeUrl.value}/edit/${row.onlyOfficeId}`;
        window.open(url);
    }
    const isFileTypeAllowed=(type:string, allowedTypes:string)=> {
        // 将allowedTypes字符串按逗号分割成数组，并去除空格
        const allowedExtensions = allowedTypes.split(',').map(ext => ext.trim());
        // 检查type是否在allowedExtensions数组中
        return allowedExtensions.includes(type);
    }
    const preview1 = (row:any) => {
        const url = `${officeUrl.value}/edit?fileId=${row.onlyOfficeId}&userName=${username.value}&mode=edit`;
        let type = row.fileName.replace('.', '')
        // console.log(url,'url',type)
        if (isFileTypeAllowed(type, fileType.value)) {
            window.open(url);
        } else {
            ElMessage({
                message: '该类型资料不能进行编辑',
                type: 'warning',
            })
        }
    }
    // 参与组织
    const deptTreeList = () => {
        deptTree().then((res) => {
            options1.value = res.data;
            if(route.query.state=='1'){
                const values = dataList[0].studyGroup.split('/'); // 分割字符串
                // console.log('===========',values)
                let currentOptions = options1.value; // 当前选项数组
                // console.log('//////////',currentOptions)
                // 遍历分割后的值，找到匹配的选项并设置到 selectedOptions
                values.forEach((value, index) => {
                    const option = currentOptions.find(item => item.name === value);
                    // console.log('----------',option.id)
                    if (option && option.children) {
                        // 如果找到匹配的选项且它有子选项，则更新 currentOptions 为子选项数组
                        currentOptions = option.children;
                    } else {
                        // 如果没有找到匹配的子选项，则停止遍历
                        return;
                    }
                })
                queryForm.studyGroupId = queryForm.studyGroupId.split('/')
            }
            // console.log('111、、、',queryForm.studyGroupId.split('/') )
        });
    };
    //专业名称
    const  getProfessionalName = () => {
        professionalnameList().then((res) => {
            Object.assign(options2, res.data)
        });
    };
    //专业等级
    // const getProfessionalGrade = async () => {
    //     // console.log(state.queryForm.majorNameId,"zymcId");
    //     const zide = state.queryForm.majorNameId;
    //     getLevel(zide).then((res) => {
    //           Object.assign(zydjnamelist, res.data)
    //         // console.log("专业等级",zydjnamelist);
    //     })
    // }
    //关键点
    const  getKeypointsList = () =>{
        keypointsListData.length = 0
        const ids = {
            zymcIds:  queryForm.majorNameIds
        }
        getKeyPointListByZymcIds(ids).then((res: any) => {
            Object.assign(keypointsListData, res.data)
        });
    }
    // 新增关键点
    const onSubmit = async () => {
        pointsformlist.value?.validate((valid:any) => {
            if (valid) {
                saveProfession(keypointsform);
				useMessage().success('提交成功!');
                centerDialogVisible.value = false;
                location.reload()
            } else {
                alert('校验失败，请检查表单项!');
                return false;
            }
        });
    };
    // 重置新增关键点form表单
    const clean1 = () => {
        pointsformlist.value.resetFields();
    }
    const getItem1=(val:any) =>{
        // console.log(val,'2222222')
        let postsString = []
        postList.forEach(item => {
            for (let i = 0; i < val.length; i++) {
                if (item.postName == val[i]) {
                    postsString.push(item.postsString)
                }
            }
        })
        queryForm.studyPostIds = postsString
    }
    const getItem2=(val:any) =>{
        // console.log(val,'33333',keypointsListData)
        let names = []
        let zydjIds = []
        let zydjNames = []
        keypointsListData.forEach(item => {
            for (let i = 0; i < val.length; i++) {
                if (item.keyId == val[i]) {
                    names.push(item.keyPoint)
                    zydjIds.push(item.zydjId)
                    zydjNames.push(item.zydjName)
                }
            }
        })
        queryForm.keyPoints = names
        queryForm.dataLevelIds = zydjIds
        queryForm.dataLevels = zydjNames
    }
    const getItem3=(val:any) =>{
        // console.log(val,'11111')
        let names = []
        options2.forEach(item => {
            for (let i = 0; i < val.length; i++) {
                if (item.zymcId == val[i]) {
                    names.push(item.zymcName)
                }
            }
        })
        queryForm.majorNames = names
        queryForm.keyPointIds = []
        getKeypointsList()
    }
    const handleCascaderChange = (item: any) => {
       if(item!==null){
           queryForm.studyGroupId = item[item.length-1]
           studyGroupIds.value = item
           if (cascaderAddr.value) {
               // console.log('yiji-----',cascaderAddr.value,cascaderAddr.value.getCheckedNodes())
               // 获取选中节点的 pathLabels
               studyGroupNames.value = cascaderAddr.value.getCheckedNodes()[0].pathLabels
               // console.log('Path Labels:', studyGroupNames.value,studyGroupIds.value);
           }
           queryForm.studyGroupIds = studyGroupIds.value
           queryForm.studyGroupNames = studyGroupNames.value
           queryForm.studyPosts.length =0
           postList.length = 0
       }else{
           queryForm.studyGroupId =undefined
           queryForm.studyPosts.length =0
           queryForm.studyPostIds.length =0
           postList.length = 0
       }
    };
    //参考组织下拉框关闭事件
    const handleVisibleChange = (isVisible:any) => {
        if (!isVisible) {
            if (cascaderAddr.value) {
                const checkedNodes = cascaderAddr.value.getCheckedNodes(); // 输出选中的节点信息
                queryForm.studyGroupId = checkedNodes[0].value
            }
            getPostList()
        }
    };
    //学习岗位
    const getPostList =  () =>{
        postList.length = 0
        if(route.query.state=='1'){
            const num = queryForm.studyGroupId.split('/')
            syspost(num[num.length-1]).then((res: any) => {
                Object.assign(postList, res.data)
            });
        }else {
            const num = queryForm.studyGroupId
            syspost(num).then((res: any) => {
                Object.assign(postList, res.data)
            });
        }
    }
    const getProfessionalGrade = (val:any) => {
        let zide = '';
        options2.forEach(item => {
            if (item.zymcName == val) {
                zide = item.zymcId
                keypointsform.zymcId = item.zymcId
                // console.log("zide",zide);
            }
        })
        if(zide){
            getLevel(zide).then((res) => {
                zydjnamelist.length = 0
                Object.assign(zydjnamelist, res.data)
                console.log(zydjnamelist,val,"zymcId1111");
            })
        }else {
            const list = {}
            Object.assign(zydjnamelist, list)
            console.log(zydjnamelist,val,"zymcId");
        }
    }
    const getProfessionalGrade1 = (val:any) => {
        let zide = '';
        zydjnamelist.forEach(item => {
            if (item.zydjName == val) {
                zide = item.zydjId
                keypointsform.zydjId = item.zydjId
                // console.log("zide",zide);
            }
        })
    }
    const fileList = ref<UploadUserFile[]>([])
    const newId = ref<string>();
    const file1 = ref('');
    // const handleChange = async (file: File, fileList: any[]) => {
    //     const formData = new FormData();
    //     formData.append('file', file.raw);
    //     try {
    //         const res = await uploadSysFile(formData);
    //         file1.value = res.data;
    //         // console.log('file1.value,成功了',file1.value)
    //     } catch (err) {
    //         console.error(err,'报错了');
    //     }
    //     fileHide.value = fileList.length >= 1;
    //     fileData.value = file1.value
    //     fileData.value.uid = file.raw.uid
    //     uploadAndGetList()
    // }
    const getFile = (val:any) =>{
        // console.log('上传成功',val)
        fileData.value = val.data
        let obj = {
            title: val.data.title,
            id: val.data.id
        }
        updateOnlyOffice(obj)
        fileData.value.onlyOfficeId = val.data.id
        fileData.value.fileName = val.data.title
        delete fileData.value.id
        // console.log('fileData.value.onlyOfficeId',fileData.value.onlyOfficeId,fileData)
        uploadAndGetList()
    }
   //获取文件标识ids
    const uploadAndGetList = async() =>{
        await uploadSysFileData(fileData.value)
            .then(res => {
                const id = res.data.data;
                idsList.push(id);
                // console.log(idsList,"idsList===========")
            }).catch((error) => {
                // 处理接口调用错误
                console.error('接口调用失败：', error);
            });
        getList()
    }
    // 获取列表
    const getList =()=>{
        const params = `ids=${idsList.join(",")}`;
         getAddList(params)
            .then(res => {
                if(res.data.data == "传的是空"){
                    dataList.length = 0
                }
                else if(res.data.false){
                    centerDialogVisible3.value = true
                Object.assign(falseList, res.data.false)
                }
                else if(res.data.ok.length>0){
                    Object.assign(dataList, res.data.ok)
                }
                // queryForm.fileAddress = dataList[0].fileAddress
            }).catch(error => {
            console.log(error)
             // 处理错误
         });
    }
    const submitBtn = ()=>{
        centerDialogVisible3.value = false
        const url = `${officeUrl.value}/delete?id=${falseList[0].onlyOfficeId}`;
        fetch(url, {
            method: 'GET', // 指定请求方法
            headers: {
                'Content-Type': 'application/json', // 根据需要设置请求头
                // 如果有认证token，也可以在这里添加
                // 'Authorization': 'Bearer YOUR_TOKEN'
            },
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Delete successful:', data);
                // 处理删除成功后的逻辑
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
                // 处理错误
            });
    }
    // watch(  () => number.value, // 观察的值
    //     (newVal, oldVal) => {
    //         // 当 keypointsform.zymcId 发生变化时，执行以下操作
    //         console.log('dataList 发生变化:', newVal, '旧值:', oldVal);
    //     },
    //     // { immediate: true } // 立即执行一次监听器，而不是等到值首次变化时才执行
    // );
    const fileRemove = (file: File, fileList: any[]) => {
        fileHide.value = fileList.length >= 1;
    }
    const fileHide = ref(false);
    //修改表格单元格
    const changeHandle = (currentRow:any)=>{
        putObj(currentRow).then((res)=>{
        })
    }
    // 清空搜索条件
    const resetQuery = () => {
        // 清空搜索条件
        queryRef.value?.resetFields()
        // 清空多选
        selectObjs.value = []
        getDataList()
    }
    // 多选事件
    const selectionChangHandle = (objs: { id: string }[]) => {
        selectObjs.value = objs.map(({ id }) => id);
        multiple.value = !objs.length;
    };
    // 删除操作
    const handleDelete = async (ids: string[],row:any) => {
        const url = `${officeUrl.value}/delete?id=${row.onlyOfficeId}`;
        fetch(url, {
            method: 'GET', // 指定请求方法
            headers: {
                'Content-Type': 'application/json', // 根据需要设置请求头
                // 如果有认证token，也可以在这里添加
                // 'Authorization': 'Bearer YOUR_TOKEN'
            },
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('Delete successful:', data);
                // 处理删除成功后的逻辑
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
                // 处理错误
            });
        try {
            await useMessageBox().confirm('此操作将永久删除');
        } catch {
            return;
        }
        try {
            await delObjs(ids).then(()=>{
                let index = 0
                while ((index = idsList.indexOf(ids[0])) !== -1) {
                    idsList.splice(index, 1); // 从数组中删除找到的元素
                }
                dataList.length = 0;
                // console.log('删除',ids[0],idsList,dataList.length,row)
                getList()
            });
            useMessage().success('删除成功');
        } catch (err: any) {
            useMessage().error(err.msg);
        }
    };
    //上传资料保存
    const uploadSysFileSubmit = () =>{
        queryRef.value?.validate((valid:any) => {
            if (valid) {
                console.log('dataList',dataList)
                if(dataList[0].timeOut >= dataList[0].minTime)
                {
                    ElMessage({
                        message: '超时提醒时长应小于最低学习时长',
                        type: 'warning',
                    })
                    return
                }
                if(queryForm.state == '0'){
                    dataList.map(item =>{
                        item.dataName = item.fileNameView
                    })
                }else {
                    queryForm.dataId = route.query.dataId
                    queryForm.fileIds.push(route.query.id)
                }
                let obj ={}
                Object.assign(obj,queryForm)
                obj.kszlFileEntityList = dataList
                // console.log('////////',queryForm,dataList)
                fileSubmit(obj).then((res) => {
                    if(res.msg=="有重复名称")
                    {
                        checkMsg.value = res.data
                        centerDialogVisible2.value = true
                    }else {
                        router.push('/train/kszlData/index');
                    }
                });
                // console.log('保存',queryForm,queryForm.studyPostIds)
            } else {
                alert('校验失败，请检查表单项!');
                return false;
            }
        });
    }
</script>
<style lang="scss" scoped>
    .my-heading {
        color: black;
        font-weight: bold;
        font-size: 26px;
        margin-bottom: 10px;
    }
    .el-form{
        margin-left: 15px;
    }
    .select1{
        width: 50px;
    }

</style>
